package org.xlp.db.xml;

import org.xlp.utils.io.path.XLPFilePathUtil;

import java.io.*;

/**
 * 解析绝对路径下sql配置文件处理器
 * @author xlp
 * @version 1.0
 */
public class FilePathSQLXmlFileHandler extends AbstractSQLXmlFileHandler{
    /**
     * 标记是具体文件
     */
    private final static String FILE_PATH_PREFIX = FilePathPrefixConstant.FILE_PATH_PREFIX;

    public FilePathSQLXmlFileHandler() {}

    /**
     * 把指定的文件描述路径转换成文件输入流
     *
     * @param sqlXmlFilePath
     * @return
     */
    @Override
    protected InputStream toInputStream(String sqlXmlFilePath) {
        if (sqlXmlFilePath.startsWith(FILE_PATH_PREFIX)) {
            sqlXmlFilePath = sqlXmlFilePath.substring(FILE_PATH_PREFIX.length());
        }

        try {
            File file = new File(sqlXmlFilePath);
            return new BufferedInputStream(new FileInputStream(file));
        } catch (Exception e) {
            throw new SQLXmlFileParseException(e);
        }
    }

    /**
     * 判断给定的路径是否符合该sql配置文件解析器，进行解析
     *
     * @param sqlXmlFilePath
     * @return 返回 true：该解析器进行解析，false：则不进行解析，交给下一个解析器去解析
     * @see AbstractSQLXmlFileHandler#handle(String, ISQLXmlFileHandlerChain)
     */
    @Override
    protected boolean match(String sqlXmlFilePath) {
        boolean match = super.match(sqlXmlFilePath);
        if (!match) return false;

        if (sqlXmlFilePath.startsWith(FilePathPrefixConstant.FILE_PATH_URL_PREFIX)
            || sqlXmlFilePath.startsWith(FilePathPrefixConstant.HTTP_PATH_PREFIX)
            || sqlXmlFilePath.startsWith(FilePathPrefixConstant.HTTPS_PATH_PREFIX)){
            return false;
        }

        if (sqlXmlFilePath.startsWith(FILE_PATH_PREFIX)){
            return true;
        }

        try {
            sqlXmlFilePath = XLPFilePathUtil.normalize(sqlXmlFilePath);
            File file = new File(sqlXmlFilePath);
            return file.exists() && file.isFile();
        } catch (Exception e) {
            return false;
        }
    }
}
